{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Longest Substring Without Repeating Characters\n",
    "\n",
    "[The Original Question](https://mp.weixin.qq.com/s/kmpUOTevA5GvoK8Y8Glmkw)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "Given a string, find the length of the longest substring without repeating characters.\n",
    "\n",
    "Can you find a solution in linear time?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def longest_substr(string: str) -> int:\n",
    "    \n",
    "    # Create a set of unique characters in the substring.\n",
    "    characters = set()\n",
    "    \n",
    "    # If there's only 1 character, return it directly.\n",
    "    length = len(string)\n",
    "    if length <= 1:\n",
    "        return length\n",
    "    \n",
    "    # Initalize the defalt length.\n",
    "    max_length = 1\n",
    "    \n",
    "    # Initalize 2 index pointers.\n",
    "    i = j = 0\n",
    "    \n",
    "    # Keep checking until both pointers reach the end.\n",
    "    while i < length and j < length:\n",
    "        if string[j] not in characters:\n",
    "            \n",
    "            # Append the next character after the substring.\n",
    "            characters.add(string[j])\n",
    "            j += 1\n",
    "            max_length = max(j - i, max_length)\n",
    "            pass\n",
    "        else:\n",
    "            \n",
    "            # Otherwise, shift the whole substring for 1 character.\n",
    "            characters.remove(string[i])\n",
    "            i += 1\n",
    "            pass\n",
    "        pass\n",
    "    return max_length"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n",
      "1\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "print(longest_substr('abcabcbb'))\n",
    "print(longest_substr('bbbbb'))\n",
    "print(longest_substr('pwwkew'))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
